import * as path from 'node:path';
import fs from 'node:fs';
import assert from 'node:assert';
import { fileURLToPath } from 'node:url';
import Printer from './Printer';

export default class PathHelper {
  static currentFileUrl = import.meta.url;
  static relativeToRoot = '../../../';

  /**
   * 获得 root 的绝对路径。root 目录指 /cli/。
   */
  static getPathAtRoot = () => {
    return fileURLToPath(new URL(PathHelper.relativeToRoot, PathHelper.currentFileUrl));
  };

  /**
   * 通过相对 root 的路径获得绝对路径。root 目录指 /cli/。
   *
   * @param relativePath 相对 root 的路径
   */
  static getPathRelativeToRoot = (...relativePaths: string[]) => {
    return path.resolve(PathHelper.getPathAtRoot(), ...relativePaths);
  };

  static getPathRelativeToDistSrc = (...relativePaths: string[]) => {
    return path.resolve(PathHelper.getPathAtRoot(), 'dist/src', ...relativePaths);
  };

  static checkFileExists = (...paths: string[]) => {
    const checkingPath = path.resolve(...paths);
    const isExists = fs.existsSync(checkingPath);
    if (!isExists) {
      Printer.error('指定的文件不存在', checkingPath);
      throw new assert.AssertionError({
        message: 'file not exists',
        operator: `fs.existsSync(${checkingPath})`,
      });
    }
    return isExists;
  };
}
